<template>
	<view class="app_main">
		<view class="navbar">
			<view class="fixed">
				<!-- 状态栏 时间 电量 信号 -->
				<view :style="{height: navbarStatusHeight+'px'}"></view>
				<!-- #ifdef H5 || APP-PLUS || MP-ALIPAY -->
				<view class="header_ele">
					<RolePlay role_Play="u-user"></RolePlay>
				</view>
				<!-- #endif -->
				<!-- #ifndef H5 || APP-PLUS || MP-ALIPAY -->
				<!-- 胶囊按钮左侧位置 -->
				<view class="navbar-content" :style="{width:navBarWidth+'px',height:navBarHeight+'px'}">
					<RolePlay role_Play="u-user"></RolePlay>
				</view>
				<!-- #endif -->
			</view>
			<!-- 设置占位 将微信小程序的状态栏高度预留出来 -->
			<view :style="{height:navbarStatusHeight+navBarHeight+'px' }"></view>
		</view>
		<view class="logo_main">
			<view class="title_log_in" v-if="loginForm.type==2">
				<p class="m_title">欢迎登录</p>
				<p class="tip">使用手机号登录</p>
			</view>
			<view class="title_log_in" v-else>
				<p class="m_title">验证码登录</p>
				<p class="tip">获取验证码</p>
			</view>
			<view class="login" v-if="loginForm.type==2">
				<uni-forms :modelValue="loginForm">
					<uni-easyinput type="number" placeholderStyle="font-size:28rpx;" v-model="loginForm.phone"
						maxlength="11" placeholder="请输入手机号" />
					<uni-easyinput type="password" placeholderStyle="font-size:28rpx;"
						@input="nextTick(()=>loginForm.password=pattern($event))" v-model="loginForm.password"
						placeholder="请输入密码" />
				</uni-forms>
			</view>
			<view class="login " v-else>
				<uni-forms :modelValue="loginForm">
					<uni-easyinput type="number" placeholderStyle="font-size:28rpx;" maxlength="11"
						v-model="loginForm.phone" placeholder="请输入手机号" />
					<view class="code_re">
						<uni-easyinput type="number" placeholderStyle="font-size:28rpx;" maxlength="6"
							:clearable="false" v-model="loginForm.code" placeholder="请输入验证码" />
						<view class="code_text" v-if="count==0" @click="getCode">
							获取验证码
						</view>
						<view class="code_text_" v-else>
							({{count}}s)后重新获取
						</view>
					</view>
				</uni-forms>
			</view>


			<view class="look_agree hint" v-if="!loginForm.type==2">
				未注册的手机号验证后自动登录
			</view>
			<view class="look_agree">
				<radio :checked="checked" @click="radioChange" style="transform: scale(.8);" color="#007cff">
				</radio>
				<view class="l_text">我已阅读并同意<view class="link_a">《服务协议》</view>和<view class="link_a">《隐私政策》</view>
				</view>
			</view>
			<view class="btn" v-if="loginForm.type==2">
				<button type="primary" :class="{btn_bg:loginForm.phone.length==11&&loginForm.password&&checked}"
					class="btn_sty" :disabled="!(loginForm.phone.length==11&&loginForm.password&&checked)"
					@click="onLogin">登录</button>
			</view>
			<view class="btn" v-else>
				<button type="primary" :class="{btn_bg:loginForm.phone.length==11&&loginForm.code.length==6&&checked}"
					class="btn_sty" :disabled="!(loginForm.phone.length==11&&loginForm.code.length==6&&checked)"
					@click="onLogin">登录</button>
			</view>
			<view class="footer">
				<view class="changeLogin" v-if="loginForm.type==2" @click="onusePhone">
					验证码登录
				</view>
				<view class="changeLogin" v-else @click="onusePassward">
					密码登录
				</view>
				<view class="forget" @click="onForget">
					忘记密码
				</view>
			</view>

		</view>
		<!-- <view class="wx_bot">
			<WechatLogin :checked="checked"></WechatLogin>
		</view> -->
	</view>
</template>

<script setup lang="ts">
	import { ref, nextTick } from "vue"
	import roleStore from '@/store/role-play.js'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import apiLogin from '@/util/api/login.js'
	import apiCode from '@/util/api/getcode.js'
	import RolePlay from '@/components/role-play/role-play.vue'
	import store from '@/store/index.js'
	import md5 from 'js-md5';
	onLoad(async (e) => {
		uni.showLoading({
			title: '加载中...'
		})
		await store.dispatch('getMobileUserHasLogin')
		roleStore.commit('set_rolePlay', 'u-user')
		if (e?.custCode) {
			uni.setStorageSync('custCode', e?.custCode)
		}
		if (uni.getStorageSync('access-network_pws')) {
			const dataValue = uni.getStorageSync('access-network_pws')
			loginForm.value.phone = dataValue.phone
			loginForm.value.password = dataValue.pws
		}
		uni.hideLoading()
	})
	const navbarStatusHeight = ref(0)
	const navBarHeight = ref(0)
	const navBarWidth = ref(375)
	onLoad(() => {
		const info = uni.getSystemInfoSync()
		navbarStatusHeight.value = info.statusBarHeight
		// 根据微信小程序的右上侧的胶囊样式 设置导航栏内容的高度
		// 条件编译 以下三个不支持胶囊样式
		// #ifndef H5 || APP-PLUS || MP-ALIPAY
		const menuInfo = uni.getMenuButtonBoundingClientRect()
		// 导航栏内容的高度 = (胶囊底部的高度 - 状态栏的高度) + (胶囊顶部的高度 - 状态栏的高度)
		navBarHeight.value = (menuInfo.bottom - info.statusBarHeight) + (menuInfo.top - info.statusBarHeight)
		// 导航栏内容的宽度  除开胶囊按钮左侧的内容宽度
		navBarWidth.value = menuInfo.left
		// #endif
	})
	// 校验密码非中文
	const pattern = (v) => {
		return v.replace(/[\u4E00-\u9FA5\s]/g, '')
	}
	const loginForm = ref({
		phone: '', //手机号 
		password: '', //登录密码
		code: "", //验证码
		accountRegistLogin: false, //账号注册并登录
		type: 2, //登录类型：1-验证码登录，2-账号密码登录
	})
	const count = ref(0) //倒计时	
	const clear = ref(null)
	const checked = ref(false)
	const radioChange = (e) => {
		checked.value = !checked.value
	}
	const loading = ref(false) //加载中
	// 跳转到重置密码
	const onForget = () => {
		uni.navigateTo({
			url: "/pages_user/login/forget?phone=" + loginForm.value.phone
		});
	}

	// 密码登录方式
	const onusePassward = () => {
		loginForm.value.type = 2
		loginForm.value.code = ''
	}
	const onusePhone = () => {
		loginForm.value.type = 1
		loginForm.value.password = ''
	}
	// 登录
	const onLogin = async () => {
		if (!/^1[^1^2]\d{9}$/.test(loginForm.value.phone)) {
			uni.showToast({
				title: '请输入正确的手机号!',
				position: 'top',
				icon: "none"
			});
			return;
		}
		if (loginForm.value.type == 2) {
			if (loginForm.value.password == '') {
				uni.showToast({
					title: '请输入登录密码!',
					position: 'top',
					icon: "none"
				});
				return;
			}
			if (!checked.value) {
				uni.showToast({
					title: '请勾选同意!',
					position: 'top',
					icon: "none"
				});
				return;
			}
			//显示加载框
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			loading.value = true
			await apiLogin.checkPhone({
				phone: loginForm.value.phone
			}).then(async res => {
				if (res.code === 20000) {
					//隐藏加载框
					loading.value = false
					if (res.data.row.registerPhone) {
						await successfullyLogin()
					} else {
						uni.navigateTo({
							url: '/pages_user/login/register?phone=' + loginForm.value.phone
						})
					}
				}

			})
			uni.hideLoading();
		} else {
			if (loginForm.value.code == '') {
				uni.showToast({
					message: '请输入验证码!',
					position: 'top'
				});
				return;
			}
			await successfullyLogin()
		}
	}
	// 获取验证码
	const getCode = async () => {
		if (!/^1[^1^2]\d{9}$/.test(loginForm.value.phone)) {
			uni.showToast({
				title: '请输入正确的手机号!',
				position: 'top',
				icon: "none"
			});
			return;
		}
		await apiLogin.checkPhone({
			phone: loginForm.value.phone
		}).then(async res => {
			//隐藏加载框
			loading.value = false
			if (res.code === 20000) {
				if (res.data.row.registerPhone) {
					count.value = 59
					clear.value = setInterval(() => {
						count.value -= 1
						if (count.value == 0) {
							clearInterval(clear.value)
						}
					}, 1000)

					await apiCode.loginCode({
						phone: loginForm.value.phone
					}).then(res => {
						if (res.code === 20000) {
							uni.showToast({
								title: res.message,
								icon: 'none',
								position: 'top',
							})
						}
					})
				} else {
					uni.redirectTo({
						url: '/pages_user/login/register?phone=' + loginForm.value.phone
					})
				}
			}

		})
	}
	// 登录成功
	const successfullyLogin = async () => {
		//显示加载框
		uni.showLoading({
			title: '加载中',
			mask: true
		});
		let data = JSON.parse(JSON.stringify(loginForm.value))
		if (loginForm.value.type == 2) {
			data.password = (md5 as any)(loginForm.value.password)
		}
		await apiLogin.login(data).then(res => {
			//隐藏加载框
			uni.hideLoading();
			if (res.code === 20000) {
				const logintime = new Date().getTime()
				let dataValue = {
					logintime: logintime, //当前登录时间戳
					token: res.data.row.tokenValue,// 设置token值
					refreshToken: res.data.row.refreshToken,//刷新token
					tokenName: res.data.row.tokenName,//token请求头
					timeToken: res.data.row.expireIn,//过期时间(秒)
				}
				uni.setStorageSync('access-network_pws', { pws: loginForm.value.type == 2 ? loginForm.value.password : '', phone: loginForm.value.phone })
				uni.setStorageSync('access-user', dataValue)
				// 登录成功后跳转
				uni.navigateTo({
					url: '/pages_user/home/home'
				})
			}
		})

	}
</script>

<style lang="scss" scoped>
	.app_main {
		width: 100%;
		height: 100vh;
		background-color: #fafafa;
		// background-image: url('@/static/network/login/bg_login.png');
		background: linear-gradient(#007cff 10%, #fff 30%);
		background-repeat: no-repeat;
		background-size: cover;
		background-position: top;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		

		.navbar {
			.fixed {
				position: fixed;
				top: 0;
				left: 0;
				z-index: 99;
				width: 100%;

				.navbar-content {
					display: flex;
					align-items: center;
				}

				.header_ele {
					height: 100rpx;
				}
			}
		}

		.logo_main {
			/* #ifdef MP-WEIXIN */
			padding: 50rpx 60rpx 20rpx;
			/* #endif */
			/* #ifndef MP-WEIXIN */
			padding: 120rpx 60rpx 20rpx;
			/* #endif */
			box-sizing: border-box;
			border-radius: 20rpx 20rpx 0 0;
			height: 100%;
			display: flex;
			flex-direction: column;
			flex: 1;

			.title_log_in {
				margin: 0rpx 0 60rpx;

				.m_title {
					font-size: 48rpx;
					color: #fff;
					font-weight: 700;
					margin-bottom: 20rpx;
				}

				.tip {
					font-size: 28rpx;
						color: #fff;
				}
			}

			.login {
				:deep(.is-input-border) {
					background-color: transparent !important;
					margin: 20rpx 0;
					border: none;
					border-bottom: 1rpx solid #ccc;
					border-radius: 0;
					height: 90rpx;

					&.is-focused {

						.uniui-clear,
						.uniui-eye-filled {
							color: #007cff99 !important;
						}
					}
				}

				.code_re {
					position: relative;

					.code_text {
						height: 30rpx;
						line-height: 30rpx;
						font-size: 28rpx;
						color: #007cff;
						position: absolute;
						top: calc(50% - 15rpx);
						right: 30rpx;
						z-index: 2;
					}

					.code_text_ {
						height: 30rpx;
						font-size: 28rpx;
						line-height: 30rpx;
						color: #999;
						position: absolute;
						top: calc(50% - 15rpx);
						right: 30rpx;
					}
				}

			}

			.hint {
				margin-left: 60rpx;
				margin-bottom: 10rpx;
			}

			.look_agree {
				display: flex;
				align-items: center;
				font-size: 24rpx;
				color: rgba(128, 128, 128, 1);
				padding-top: 20rpx;

				.l_text {
					display: flex;
					align-items: center;

					.link_a {
						color: #007cff;
					}
				}
			}

			.btn {
				margin-top: 20rpx;

				.btn_sty {
					border-radius: 90rpx;
					background-color: #007cff6b;
					line-height: 90rpx;
					height: 90rpx;
					font-size: 32rpx;
					color: #fff;
				}

				:deep(button::after) {
					border: none !important;
				}

				.btn_bg {
					background-color: #007cff;
				}
			}

			.footer {
				margin: 40rpx 0;
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 24rpx;

				.forget {
					color: #007cff;
				}

				.changeLogin {
					color: #007cff;
				}
			}
		}

		.wx_bot {
			margin-top: 10%;
		}
	}

	:deep(.uni-select) {
		border: none !important;
		padding: 0;

		.uni-icons {
			display: none;
		}

		.uni-select__input-placeholder {
			text-align: right;
			margin-right: 12rpx;
			font-size: 28rpx;
			color: #999;
		}

		.uni-select__input-text {
			text-align: right;
			margin-right: 12rpx;
			color: #fff;
		}

		.uni-popper__arrow {
			left: 20%;
		}

		.uni-select__selector {
			top: 100%;
			width: 180rpx;
		}
	}
</style>